package pers.bbw.crr.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.code.kaptcha.Producer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;
import pers.bbw.crr.dao.UserMapper;
import pers.bbw.crr.dto.UserSearchDto;
import pers.bbw.crr.entity.User;
import pers.bbw.crr.service.UserService;
import pers.bbw.crr.util.FileUtil;
import pers.bbw.crr.util.IpUtil;
import sun.misc.BASE64Encoder;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * userService业务层处理
 *
 * @author bbw
 * @date 2024-12-13
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private Producer producer;

    /**
     * 查询user
     *
     * @param id user主键
     * @return user
     */
    @Override
    public User selectUserById(int id) {
        return userMapper.selectUserById(id);
    }

    /**
     * 查询user列表
     *
     * @param user user
     * @return user
     */
    @Override
    public PageInfo<User> selectUserList(UserSearchDto dto) {
        User user = new User();
        BeanUtil.copyProperties(dto, user);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        PageInfo<User> userPageHelper = new PageInfo<>(userMapper.selectUserList(user));
        return userPageHelper;
    }

    /**
     * 新增user
     *
     * @param user user
     * @return 结果
     */
    @Override
    public void insertUser(User user, MultipartFile file) {
        saveAndUpload(user, file);
    }

    /**
     * 修改user
     *
     * @param user user
     * @return 结果
     */
    @Override
    public void updateUser(User user, MultipartFile file) {
        saveAndUpload(user, file);
    }

    /**
     * 批量删除user
     *
     * @param ids 需要删除的user主键
     * @return 结果
     */
    @Override
    public int deleteUserByIds(int[] ids) {
        return userMapper.deleteUserByIds(ids);
    }

    /**
     * 删除user信息
     *
     * @param id user主键
     * @return 结果
     */
    @Override
    public int deleteUserById(int id) {
        return userMapper.deleteUserById(id);
    }

    /**
     * 获取验证码
     * @author 白博文 0205
     * @param request
     * @return
     * @throws IOException
     */
    @Override
    public Map<Object, Object> captcha(HttpServletRequest request) throws IOException {
        String code = producer.createText();
        BufferedImage image = producer.createImage(code);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        BASE64Encoder encoder = new BASE64Encoder();
        String str = "data:image/jpeg;base64,";
        String base64Img = str + encoder.encode(outputStream.toByteArray());
        redisTemplate.opsForValue().set(IpUtil.getIpAddr(request), code, 120, TimeUnit.SECONDS);
        return MapUtil.builder()
                .put("code", code)
                .put("captcherImg", base64Img)
                .build();
    }

    private void saveAndUpload(User user, MultipartFile file) {
        if (user.getId() == null) {//新增
            if (file != null) {
                String createFileUrl = FileUtil.upload(file);
                user.setFileUrl(createFileUrl);
            }
            user.setCreateTime(new Date());
            userMapper.insertUser(user);
        } else {//修改
            String fileUrl = userMapper.selectFileUrlById(user.getId());
            if (StrUtil.isNotEmpty(fileUrl)) {//原图片为空
                FileUtil.delete(fileUrl);
            }
            if (file != null) {
                String updateFileUrl = FileUtil.upload(file);
                user.setFileUrl(updateFileUrl);
            }
            user.setUpdateTime(new Date());
            userMapper.updateUser(user);
        }

    }

    /**
     * 用户注册
     * @author 白博文 0205
     * @param user
     * @param file
     * @return
     */
    @Override
    public boolean register(User user, MultipartFile file) {
        if (BeanUtil.isEmpty(userMapper.selectUserByUserName(user.getUsername()))) {
            String pwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
            user.setPassword(pwd);//加密存储
            if (file != null) {
                String createFileUrl = FileUtil.upload(file);
                user.setFileUrl(createFileUrl);
            } else {
                user.setFileUrl("/file/屏幕截图 2024-12-14 230224.png"); //默认头像
            }
            user.setCreateTime(new Date());
            userMapper.insertUser(user);
            return true;
        } else {
            return false;
        }

    }

    /**
     * 登录
     * @author 白博文 0205
     * @param loginInfo
     * @param request
     * @return
     */
    @Override
    public int loginCheck(Map<String, String> loginInfo, HttpServletRequest request) {
        String username = loginInfo.get("username");
        String password = loginInfo.get("password");
        String code = loginInfo.get("code");
        User user = userMapper.selectUserByUserName(username);
        if (!DigestUtils.md5DigestAsHex(password.getBytes()).equals(user.getPassword())) { //账号密码错误
            return 0;
        }
        String captcha = (String) redisTemplate.opsForValue().get(IpUtil.getIpAddr(request));
        if (StrUtil.isBlank(captcha)) { // 验证码已失效
            return 1; //验证码失效
        }
        if (!code.equals(captcha)) {
            return 2; //验证码错误
        }
        return 3; //登录成功
    }
}
